<?php

namespace app\admin\controller;

use app\models\{Goods, GoodsSpec};
use think\Controller;
use think\facade\Env;
use think\Db;
use oss\Oss;
use app\facade\Redis;

class Base extends Controller
{

    public function initialize()
    {
        $menu = config('menu.menu');
        $controller = strtolower($this->request->controller());
        $action = strtolower($this->request->action());
        $path = [];
        if (isset($menu[$controller])) {
            $path['c'] = $menu[$controller]['name'] ?: null;
            $path['a'] = $menu[$controller]['sub'][$action]['name'] ?: null;
            $path['s'] = $menu[$controller]['sub'][$action]['show'] ?: null;
        }
        $this->assign('path', $path);
    }

    protected function get_rand_str($len = 6)
    {
        $arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'), array('$', '@', '#', '%', '&'));
        shuffle($arr);
        $sub_arr = array_slice($arr, 0, $len);
        return implode('', $sub_arr);
    }

    //图片上传
    public function upload_img()
    {
        if ($this->request->isPost()) {
            if (empty($_FILES['file'])) {
                return json(['code' => 1, 'status' => 1, 'msg' => '参数错误']);
            }
            $file = $_FILES['file'];
            $oss = new Oss();
            $oss->setUploadType('ram');
            $url = $oss->uploadPostFile($file, 'lxc/' . date('Y-m-d'));
            return json(['code' => 0, 'status' => 0, 'data' => ['src' => $url]]);
            // $file = request()->file('file');
            // $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
            // $info = $file->validate(['size' => 1024 * 1024 * 5, 'ext' => 'jpg,png,gif,jpeg'])
            //     ->move($path);
            // if (!$info) {
            //     return json(['code' => 1, 'status' => 0, 'data' => []]);
            //     $this->result([], 1, $file->getError());
            // } else {
            //     $url = '/uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
            //     $url = url($url, '', '', false);
            //     $url = "https://" . Env('app.api_url') . $url;
            //     return json(['code' => 0, 'status' => 0, 'data' => ['src' => $url]]);
            // }
        }
    }

    public function getgoods()
    {
        $id = array_filter(input('id') ?? []);
        $list = (new Goods())->where('g.isdel', 1)
            ->where(['g.id' => $id])->alias('g')
            ->join('GoodsSpec gs', 'gs.goodid = g.id')
            ->field('g.*,gs.name,gs.price,gs.stock,gs.unmit,gs.starbuy')
            ->select();
        foreach ($list as $item) {
            $images = json_decode($item['images'], true) ?? [];
            $item['images'] = $images[0] ?? '';
        }
        return json(['status' => 0, 'data' => $list]);
    }
}
